import re

from rest_framework import serializers

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from django_redis import get_redis_connection

from utils.openid_decode_encode import decode_sign_openid


class OAuthQQUserSerializer(serializers.Serializer):
    sms_code = serializers.CharField(write_only=True, label='短信验证码')
    access_token = serializers.CharField(label='加密后的openid')
    mobile = serializers.RegexField(label="手机号",regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(min_length=8, max_length=20, label="密码")


    #多字段校验
    def validate(self, attrs):
        #获取数据
        mobile=attrs.get("mobile")
        password=attrs.get("password")
        sms_code=attrs.get("sms_code")
        openid=attrs.get("access_token")

        #判断openid是否存在
        if not openid:
            raise serializers.ValidationError("openid错误")


        # 获取redis对象
        redis_connection = get_redis_connection("code")
        # 获取redis的短信验证码
        redis_sms_code = redis_connection.get("sms_code_%s" % mobile)

        # 判断短信验证码是否过期
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")
        # 判断用户填写的短信验证码是否正确
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码填写错误")

        #校验密码
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as  e:
           pass
        else:
            #如果找到用户对象，则判断密码
            if not user.check_password(password):
                raise serializers.ValidationError("密码错误")

        return attrs


    def create(self, validated_data):
        #获取数据
        mobile=validated_data.get("mobile")
        password=validated_data.get("password")
        openid=validated_data.get("access_token")

        #根据手机号查询用户，判断是否已经存在用户
        try:
            user=User.objects.get(mobile=mobile)
        except Exception as  e:
            #没有用户，则流氓创建新用户
            user=User.objects.create(mobile=mobile,username=mobile,password=password)
            user.set_password(password)
            user.save()

        #openid解密
        decode_openid=openid=decode_sign_openid(openid)

        #用户已经存在，则绑定
        OAuthQQUser.objects.create(openid=decode_openid,user_id=user.id)

        #生成jwt
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


